package com.weilan.ark3.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.weilan.ark3.entity.ModbusConf;
import com.weilan.ark3.mapper.ModbusConfMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import java.util.ArrayList;
import java.util.List;

/**
 * @Date 2023/3/4 19:20
 * @Description: 点表入库监听器
 */
@Slf4j
public class ExcelModelListener extends AnalysisEventListener<ModbusConf> {

    List<ModbusConf> modbusConfList = new ArrayList<>();

    private ModbusConfMapper modbusConfMapper;

    private String sheetName;


    public ExcelModelListener(ModbusConfMapper modbusConfMapper, String sheetName) {
        this.modbusConfMapper = modbusConfMapper;
        this.sheetName = sheetName;
    }


    @Override
    public void invoke(ModbusConf modbusConf, AnalysisContext context) {
        modbusConfList.add(modbusConf);
    }

    /**
     * 所有数据解析完成了存库
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (sheetName == null) {
            sheetName = analysisContext.readSheetHolder().getSheetName();
        }
        log.info("读取到{}， {}条数据，开始存储数据库！", sheetName, modbusConfList.size());
        for (ModbusConf modbusConf : modbusConfList) {
            String addr = modbusConf.getAddr();
            ModbusConf conf = modbusConfMapper.selectOne(new LambdaQueryWrapper<ModbusConf>().eq(ModbusConf::getAddr, addr));
            if (ObjectUtils.isEmpty(conf)) {
                modbusConf.setModuleName(sheetName);
                modbusConfMapper.insert(modbusConf);
            }
        }
        log.info("存储数据库成功！");
    }

}